package com.iraytek.rtspdemo;

import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.iraytek.gles.ImageCallback;
import com.iraytek.gles.render.YuvRender;

import java.nio.ByteBuffer;

/**
 * created by yhy on 2021/1/25
 */
public class ImageAvailableListener implements ImageReader.OnImageAvailableListener, Handler.Callback {
    private static final String TAG = "ImageAvailableListener";
    private YuvRender render;
    private ImageData imageData;
    private Handler handler;
    private ImageCallback<byte[]> imageCallback;

    public ImageAvailableListener(YuvRender render) {
        this.render = render;
        imageData = new ImageData();
        HandlerThread thread = new HandlerThread("camera-data");
        thread.start();
        handler = new Handler(thread.getLooper(), this);
    }

    public void setImageCallback(ImageCallback<byte[]> imageCallback) {
        this.imageCallback = imageCallback;
    }

    public void quit() {
        handler.getLooper().quit();
    }

    @Override
    public void onImageAvailable(ImageReader reader) {
        Image image = reader.acquireLatestImage();
        if (image == null) {
            return;
        }

        Image.Plane[] planes = image.getPlanes();
        Image.Plane plane = planes[0];
        ByteBuffer buffer = plane.getBuffer();
        int capacity = buffer.capacity();
        int w = image.getWidth();
        int h = image.getHeight();
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "onImageAvailable: " + capacity);
        }
        /*//inf模式下不需要可见光数据，而rgb模式仍需要红外数据做防强光判断
        if (!inf && imageProcessor.getMode() == ImageProcessor.Mode.INF) {
            image.close();
            return;
        }*/
        byte[] data;//create new to avoid read/write on multi threads
        if (planes.length > 1) {//yuv
            data = new byte[capacity * 3 / 2];
            buffer.get(data, 0, capacity);

            buffer = planes[1].getBuffer();
            buffer.get(data, capacity, buffer.capacity());
        } else {
            data = new byte[capacity];
            buffer.get(data);
        }
        image.close();
        imageData.fill(data, w, h);

        handler.sendEmptyMessage(100);

    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if (msg.what == 100) {
            if (render.prepared()) {
                byte[] data = imageData.getData();
                render.onImagePixesChange(data, imageData.getWidth(), imageData.getHeight());
                if (imageCallback != null) {
                    imageCallback.onImagePixesChange(data, imageData.getWidth(), imageData.getHeight());
                }
            }
        }
        return true;
    }
}
